package com.dfdchem.imd.kaiwu.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivityAnon;
import com.dfdchem.imd.kaiwu.application.KWApp;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.manager.GlideManager;
import com.dfdchem.imd.kaiwu.model.FileModel;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.model.UserFeedback;
import com.dfdchem.imd.kaiwu.util.FileUtil;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.StringUtil;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.vansz.glideimageloader.GlideImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import zuo.biao.library.util.CommonUtil;

@RequiresApi(api = Build.VERSION_CODES.M)
@Route(path = RouterPath.FEEDBACK_ACTIVITY)
public class FeedbackActivity extends BaseActivityAnon implements RadioGroup.OnCheckedChangeListener, TextWatcher, View.OnClickListener, OnHttpResponseListener {

    private static final String TAG = "FeedbackActivity";

    private String feedback_title;
    private RadioGroup feedback_type;
    private EditText feedback_content;
    private TextView feedback_content_counter;

    private Button submit;
    private View feedback_image_add;

    private LinearLayout imageLayoutParent;
    private List<RelativeLayout> imageLayouts;
    private List<String> imageUrls;
    private BottomSheetDialog bottom_sheet_dialog;

    private final static int request_code_upload_image = 1;
    private final static int request_code_user_feedback = 2;

    private Transferee transfer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);

        initView();
        initData();
        initEvent();

        transfer = Transferee.getDefault(FeedbackActivity.this);
    }

    @Override
    public void initView() {
        submit = findView(R.id.submit);

        feedback_type = findView(R.id.feedback_type);
        feedback_content = findView(R.id.feedback_content);
        feedback_content_counter = findView(R.id.feedback_content_counter);

        feedback_image_add = findView(R.id.feedback_image_add);
        imageLayoutParent = findView(R.id.imageLayoutParent);
    }

    @Override
    public void initData() {
        imageLayouts = new ArrayList<>();
        imageUrls = new ArrayList<>();
    }

    @Override
    public void initEvent() {
        feedback_content.addTextChangedListener(this);
        feedback_type.setOnCheckedChangeListener(this);
        feedback_image_add.setOnClickListener(this);
        submit.setOnClickListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        Log.d(TAG, "onCheckedChanged group:" + group + "checkedId:" + checkedId);
        RadioButton rb = group.findViewById(checkedId);
        Log.d(TAG, rb.getText() + "");
        this.feedback_title = rb.getText().toString();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @SuppressLint("DefaultLocale")
    @Override
    public void afterTextChanged(Editable s) {
        if (s == null) {
            return;
        }
        int count = s.length();
        feedback_content_counter.setText(String.format("%d/240", count));
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.feedback_image_add:
                if (bottom_sheet_dialog == null) {
                    bottom_sheet_dialog = new BottomSheetDialog(this);
                    View view = getLayoutInflater().inflate(R.layout.sheet_dialog, null);
                    bottom_sheet_dialog.setContentView(view);
                    bottom_sheet_dialog.show();

                    Button bottom_sheet_cancel = view.findViewById(R.id.bottom_sheet_cancel);
                    bottom_sheet_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bottom_sheet_dialog.dismiss();
                        }
                    });

                    Button bottom_sheet_camera = view.findViewById(R.id.bottom_sheet_camera);
                    Button bottom_sheet_photo = view.findViewById(R.id.bottom_sheet_photo);

                    bottom_sheet_camera.setOnClickListener(this);
                    bottom_sheet_photo.setOnClickListener(this);
                }
                bottom_sheet_dialog.show();

                if (imageLayouts.size() >= 3) {
                    return;
                }
                /*View view = getLayoutInflater().inflate(R.layout.feedback_image, imageLayoutParent, false);
                if (view instanceof RelativeLayout) {
                    RelativeLayout imageLayout = (RelativeLayout) view;

                    imageLayout.setBackgroundColor(getColor(colors[imageLayouts.size()]));
                    Button clear = imageLayout.findViewById(R.id.feedback_image_clear);
                    clear.setTag(imageLayout);
                    clear.setOnClickListener(this);
                    imageLayoutParent.addView(imageLayout);
                    imageLayouts.add(imageLayout);
                    if (imageLayouts.size() >= 3) {
                        feedback_image_add.setVisibility(View.GONE);
                    }
                }*/
                break;
            case R.id.feedback_image_clear:
                RelativeLayout imageLayout = (RelativeLayout) v.getTag(R.id.tag_feedback_image_layout);
                String imageUrl = (String) v.getTag(R.id.tag_feedback_image_url);

                imageLayoutParent.removeView(imageLayout);
                imageLayouts.remove(imageLayout);
                imageUrls.remove(imageUrl);

                if (imageLayouts.size() < 3) {
                    feedback_image_add.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.bottom_sheet_camera:
                bottom_sheet_dialog.dismiss();
                selectPicFromCamera();
                break;
            case R.id.bottom_sheet_photo:
                bottom_sheet_dialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE_PHOTO);
                break;
            case R.id.submit:
                submit.setEnabled(false);
                submit.setTextColor(Color.GRAY);
                User user = DataManager.getInstance().getUser();
                if (user == null) {
                    showShortToast("请登录");
                    return;
                }

                if (StringUtil.isEmpty(this.feedback_title)) {
                    showShortToast("请选择你要反馈的问题类型");
                    return;
                }

                if (StringUtil.isEmpty(feedback_content.getText().toString())) {
                    showShortToast("请补充详细的问题内容，不少于6个字");
                    return;
                }

                UserFeedback uf = new UserFeedback();
                uf.setTitle(this.feedback_title);
                uf.setContent(feedback_content.getText().toString());
                uf.setName(user.getUserName());
                uf.setPhoneNo(user.getPhone());
                if (imageUrls != null && imageUrls.size() > 0) {
                    uf.setAttachmentList(JSON.toJSONString(imageUrls));
                }

                Log.d(TAG, "uf:" + JSON.toJSONString(uf));

                runThread("userFeedback", new Runnable() {
                    @Override
                    public void run() {
                        RequestUtil.feedback(uf, request_code_user_feedback, FeedbackActivity.this);
                    }
                });

                break;
        }
    }

    private File cameraFile;
    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtil.isExitsSdcard()) {
            showShortToast("SD卡不存在，不能拍照");
            return;
        }

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        File cacheDir = KWApp.getInstance().getExternalCacheDir();
        if (cacheDir != null && !cacheDir.exists()) {
            cacheDir.mkdirs();
        }

        cameraFile = new File(cacheDir.getAbsolutePath(), "photo-" + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();

        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, KWApp.getInstance().getApplicationInfo().packageName + ".fileProvider", cameraFile);
        } else {
            uri = Uri.fromFile(cameraFile);
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_PHOTO = 19;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_CAMERA:
                    if (cameraFile != null && cameraFile.exists()) {
                        String picturePath = cameraFile.getAbsolutePath();
                        Log.d(TAG, "REQUEST_CODE_CAMERA length:" + FileUtil.getFileSize(picturePath));

                        Luban.with(FeedbackActivity.this)
                                .load(new File(picturePath))
                                .ignoreBy(1000)
                                .setTargetDir(cameraFile.getParent())
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        showProgressDialog("正在处理图片...");
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        dismissProgressDialog();
                                        Log.d(TAG, "OnCompressListener onSuccess:" + FileUtil.getFileSize(file.getPath()));
                                        uploadImage(file.getAbsolutePath());
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }
                                }).launch();
                    }
                case REQUEST_CODE_PHOTO:
                    if (data != null) {
                        Uri selectedImage = data.getData();
                        if (selectedImage != null) {
                            String picturePath = getPathFromUri(selectedImage);

                            uploadImage(picturePath);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private String lastPicPath;

    /**
     * 上传图片到服务器
     * @param filePath
     */
    private void uploadImage(String filePath){
        showProgressDialog("正在上传，请稍后...");
        lastPicPath = filePath;
        runThread(TAG + "uploadImage", new Runnable() {
            @Override
            public void run() {
                RequestUtil.uploadFile(
                        FileUtil.getFileFullName(filePath),
                        FileUtil.getMimeType(filePath),
                        filePath,
                        request_code_upload_image,
                        FeedbackActivity.this);
            }
        });
    }

    /**
     * 根据图库图片uri获取图片路径
     * @param selectedImage
     */
    private String getPathFromUri(Uri selectedImage) {
        if (selectedImage == null) {
            return null;
        }
        String picturePath = null;
        Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex("_data");
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        } else {
            if (selectedImage.getPath() != null) {
                File file = new File(selectedImage.getPath());
                if (!file.exists()) {
                    Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();

                }
                picturePath = file.getAbsolutePath();
            }
        }
        return picturePath;
    }

    @Override
    protected void onDestroy() {
        if (bottom_sheet_dialog != null) {
            bottom_sheet_dialog.dismiss();
        }

        transfer.destroy();
        super.onDestroy();
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {

        if (requestCode == request_code_upload_image) {
            dismissProgressDialog();
        }
        if (e != null) {
            Toast.makeText(getActivity(), "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_upload_image:
                Resp<FileModel> fileModelResp = JSON.parseResp(resultJson, FileModel.class);
                Log.d(TAG, "onHttpResponse fileModelResp:" + fileModelResp);
                if (fileModelResp != null && fileModelResp.getCode() == 200 && fileModelResp.getData() != null) {
                    View view = getLayoutInflater().inflate(R.layout.feedback_image, imageLayoutParent, false);
                    if (view instanceof RelativeLayout) {

                        RelativeLayout imageLayout = (RelativeLayout) view;

                        Button clear = imageLayout.findViewById(R.id.feedback_image_clear);
                        ImageView imageView = imageLayout.findViewById(R.id.feedback_image);
                        clear.setTag(R.id.tag_feedback_image_layout, imageLayout);

                        clear.setOnClickListener(this);
                        imageLayoutParent.addView(imageLayout);
                        imageLayouts.add(imageLayout);
                        if (imageLayouts.size() >= 3) {
                            feedback_image_add.setVisibility(View.GONE);
                        }

                        String fileUrl = RequestUtil.url_file + "/" + fileModelResp.getData().getUrl();
                        clear.setTag(R.id.tag_feedback_image_url, fileUrl);
                        imageUrls.add(fileUrl);

                        if (lastPicPath != null && FileUtil.getFileSize(lastPicPath) == fileModelResp.getData().getSize()) {
                            new GlideManager(imageLayout).load(imageView, lastPicPath);
                        } else {
                            new GlideManager(imageLayout).load(imageView, fileUrl);
                        }

                        List<String> urlList = new ArrayList<>();
                        // urlList.add(fileUrl);
                        urlList.add(lastPicPath);

                        imageView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                transfer.apply(TransferConfig.build()
                                        .setImageLoader(GlideImageLoader.with(getApplicationContext()))
                                        .setSourceUrlList(urlList)
                                        .create()
                                ).show();
                            }
                        });
                    }
                }

                break;
            case request_code_user_feedback:
                Resp<String> result = JSON.parseResp(resultJson, String.class);
                if (result != null && result.getCode() == 200 && result.getData() != null) {
                    showShortToast(result.getMsg() == null ? "反馈成功" : result.getMsg());
                    finish();
                }
                break;
        }
    }
}
